﻿using System.Net;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using suanpan.API.Components.Exceptions;
using System.Xml;
namespace suanpan.API.Components.Behaviors.ErrorHandling
{
    public class RestErrorMessage : Message
    {
        #region Properties

        private HttpStatusCode statusCode;
        public HttpStatusCode StatusCode { get { return statusCode; } set { statusCode = value; } }

        private string errorMessage;
        public string ErrorMessage { get { return errorMessage; } set { errorMessage = value; } }

        private MessageHeaders headers;
        private MessageProperties properties;
        private MessageVersion version;

        #endregion

        #region CTors
        
        public RestErrorMessage(RESTException restException)
            :this(restException.StatusCode, restException.StatusDescription, restException.StatusDescription){}

        public RestErrorMessage(HttpStatusCode statusCode, string errorMessage, string statusDescription)
        {
            this.StatusCode = statusCode;
            this.ErrorMessage = errorMessage;
            version = MessageVersion.None;
            headers = new MessageHeaders(version);
            properties = new MessageProperties();
            if (WebOperationContext.Current != null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = statusCode;
                if (!string.IsNullOrEmpty(statusDescription))
                    WebOperationContext.Current.OutgoingResponse.StatusDescription = statusDescription;
                WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = false;
            }
            else
            {
                HttpResponseMessageProperty prop = new HttpResponseMessageProperty();
                prop.StatusCode = statusCode;
                this.Properties[HttpResponseMessageProperty.Name] = prop;

            }
        }

        #endregion

        #region Virtual Overrides
        public override MessageHeaders Headers
        {
            get { return headers; }
        }

        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("error");
            writer.WriteAttributeString("xmlns", "api.restchess.com");
            writer.WriteElementString("statuscode", string.Format("{0}", (int)statusCode));
            writer.WriteElementString("message", errorMessage);
            writer.WriteEndElement();
        }
        public override MessageProperties Properties
        {
            get { return properties; }
        }
        public override MessageVersion Version
        {
            get { return version; }
        }
        #endregion
    }
}
